package org.example.structure.flyweight;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 类描述：数据库连接池
 * <br>
 *
 * @author ZS
 * @version 1.0
 * @date 2020/12/30
 **/
public class DataSourcePool {
    private List<Connection> pool;

    private String url = "jdbc:mysql://localhost:3306/test";
    private String username = "root";
    private String password = "1234";
    private String driverClassName = "com.mysql.cj.jdbc.Driver";

    private final int poolSize = 20;

    public DataSourcePool() {
        pool = new LinkedList<Connection>();

        try {
            Class.forName(driverClassName);
            for (int i = 0; i < poolSize; i++) {
                Connection connection = DriverManager.getConnection(url, username, password);
                pool.add(connection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized Connection getConnection(){
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        }
        return null;
    }

    public synchronized void release(Connection connection) {
        pool.add(connection);
    }
}
